//
//  WBNetworkingManager.swift
//  CustomWeiBo
//
//  Created by laiqiang on 21/5/16.
//  Copyright © 2021年 laiqiang. All rights reserved.
//

import UIKit
import AFNetworking

//swift支持任意数据类型，oc内只支持int数据
enum WBHTTPMethod {
    case GET
    case POST
}


class WBNetworkingManager: AFHTTPSessionManager {
    //静态 常量 闭包 第一次访问时执行闭包，结果保存在share 常量中
    static let share: WBNetworkingManager = { //构建初始化闭包
        
        let instance = WBNetworkingManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
        }()

    var accessToken: String?// = "2.00lM_1xGahuflB3fd8edbfdd_xPQ5B"
    
    //用户 id
    var uid: String? = "1620610038"
    
    lazy var userAccount = WBUserAccount()
    
    //是否登录了
    var userLogin: Bool {
        
        //FIXME:
        return true
        return accessToken != nil
    }
    
    //专门负责拼接token 的网络请求方法
    func tokenRequest(method:WBHTTPMethod = .GET,URLString:String,parameters: [String:Any]?,completion:@escaping (_ json:Any?,_ isSuccess:Bool)->()) {
        
        //处理token 字典
        //1判断 字典 是否存在，不存在就创建一个
        //FIXME:
        userAccount.account_token = "2.00lM_1xGahuflB1d3e0e6011rbuYkD"
        
        guard let token = userAccount.account_token else {
            
            //发送通知,提示用户登录
            print("没有token,需要登录")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            completion(nil, false)
            return
        }
        
        var params = parameters
        if params == nil {
            
            params = [String:Any]()
        }
        params!["access_token"] = token
        
        //使用request方法，发起真正的网络请求
        request(method: method, URLString: URLString, parameters: params!, completion: completion)
    }
    
    //有可能没有数据，所以Any? ,前面的 “_” 表示参数提示，"json:"表示参数名，类似" 提示viewbuildwith 参数json:"
    /* AFN 的GET/POST 请求
     
     *   - method: GET/POST
     *   - URLString: url路径
     *   - parameters: url尾部参数，字典
     *   - completion: 回调 网络请求数据，是否成功
    */
    func request(method:WBHTTPMethod = .GET,URLString:String,parameters: [String:Any],completion:@escaping (_ json:Any?,_ isSuccess:Bool)->()) {
       
        //闭包
        let success = {(task:URLSessionDataTask,json:Any?)->() in
        
            completion(json, true)
        }
        
        let failure = {(task:URLSessionDataTask?,error:Error)->() in
            
            //处理 403 token过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token过期了~~~")
                
                //发送通知,提示用户再次登录(不知道谁调用的，谁收到通知，水处理)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad token")
                
            }
            
            //不传出去，因为error比较吓人，如：xxxxx，错误全是英文
            print("网络错误\(error)")
            
            completion(nil, false)
        }

        if method == .GET {
            
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        else{
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        
        }
    }
    
    
    func unreadCount(completion:@escaping (_ count:Int)->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlstring = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let parms = ["uid":uid]
//        print("url:\(urlstring) 参数\(parms)")
        tokenRequest(URLString: urlstring, parameters: parms) { (json, isSuccess) in
            
            let dict = json as? [String : AnyObject]
            let count = dict?["status"] as? Int
            completion(count ?? 0)
        }
    }
}

//用户信息 -登陆后执行
extension WBNetworkingManager{

    func loadUserInfo(completion:@escaping (_ dict:[String : AnyObject])->()) {
        
        guard let uid = userAccount.uid else {
           return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid":uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSucces) in
            
            print(json ?? "")
            completion((json as? [String : AnyObject]) ?? [:])
        }
    }
}

//oauth账号相关
extension WBNetworkingManager {

    func loadAccessToken(code: String , completion:@escaping (_ isSuccess: Bool)->()) {
        
        let URLString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":WBAppKey,
                      "client_secret":WBAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WBredirect_uri]
        request(method: .POST, URLString: URLString, parameters: params) { (json, isSuccess) in
            
            self.userAccount.yy_modelSet(with: (json as? [String : AnyObject]) ?? [:])

            self.loadUserInfo(completion: { (dict) in
                
                print(dict)
                self.userAccount.yy_modelSet(with: (dict))
                
                self.userAccount.saveAccount()
                
                completion(isSuccess)
            })
            
            print(self.userAccount)
            
        }
    }
}
